<?php

namespace app\api\controller;


use app\admin\model\SystemConfig;
use app\common\business\Address;
use app\common\business\Agreement;
use app\common\business\Cate;
use app\common\business\Goods;
use app\common\business\GoodsApply;
use app\common\business\Manager;
use app\common\business\Member;
use app\common\business\Membercard;
use app\common\business\Membercardxz;
use app\common\business\MemberPaylog;
use app\common\business\Orders;
use app\common\business\Wechat;
use app\common\lib\ArrClass;
use app\common\lib\Show;
use app\common\lib\Status;
use app\common\lib\Str;
use app\common\model\MallGroupsOrder;
use app\common\model\MallGroupsOrderRefund;
use app\common\model\MallManager;
use app\common\model\MallOrderRefund;
use app\common\model\MallWithdrawal;
use const Grpc\STATUS_ABORTED;

class User extends Base
{
    /**
     * @return \think\response\Json
     */
    public function getUserInfo()
    {
        $param = $this->request->param();
        $data = $param['userInfo'];
        $data['openid'] = $param['openid'];
        try {
            $wechat = (new Wechat())->WechatByOpenid($data);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, "获取失败");
        }


        return Show::json_show(Status::mini_normal, "获取用户信息成功", $wechat);
    }

    /**
     * 获取用户信息
     * @return \think\response\Json
     */
    public function getMemberInfo(){
        $openid = $this->request->param('openid','','trim');
        try {
            $wechat = (new Wechat())->getOpenidById($openid);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, "获取失败");
        }
        $cardinfo =(new Membercard())->getMembercardInfo($wechat['usertype']);
        $wechat['usertypename'] = $cardinfo['title'];
        return Show::json_show(Status::mini_normal, "获取用户信息成功", [
            'wechat'=>$wechat
        ]);
    }

    /**
     * 获取提现规则
     * @return \think\response\Json
     */
    public function getWithdrawalRule(){
        $openid =$this->request->param('openid','','trim');
        try{
            $withdrawal_desc =(new Member())->getSystenConfig('withdrawal_desc');
            $member =(new Wechat())->getOpenidById($openid);
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error, $e->getMessage());
        }
        return Show::json_show(Status::mini_normal, "获取用户信息成功", [
            'desc'=>htmlspecialchars_decode($withdrawal_desc),
            'balance' =>$member['balance']
        ]);
    }


    /**
     * 解密手机号
     * @return \think\response\Json
     */
    public function getMobile(){
        $code =$this->request->param('code','','trim');
        $iv =$this->request->param('iv','','trim');
        $openid =$this->request->param('openid','','trim');
        $encryptedData =$this->request->param('encryptedData','','trim');
        $session=$this->mini_app->auth->session($code);

        $decryptedData = $this->mini_app->encryptor->decryptData($session['session_key'], $iv, $encryptedData);
        if($decryptedData && isset($decryptedData['phoneNumber'])){
            (new Wechat())->getOpenidUpdateMobile($openid,$decryptedData['phoneNumber']);
        }
        return Show::json_show(Status::mini_normal, "获取用户信息成功", [
            'data'=>$decryptedData
        ]);
    }


    /**
     * 获取用户权益
     * @return void
     */
    public function memberCard(){
        $openid = $this->request->param('openid','','trim');
        try {
            $userinfo = (new Wechat())->getOpenidById($openid);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, "获取失败");
        }
        $usercardinfo=[];
        if($userinfo && $userinfo['usertype']>0){

            $cardinfo=(new Membercard())->getMembercardInfo($userinfo['usertype']);

            $usercardinfo['usertypename'] =$cardinfo['title'];
            $usercardinfo['overtime'] = date('Y/m/d',$userinfo['overtime']);
        }else{
            $usercardinfo['usertypename'] ='普通会员';
        }
        $cardlist =(new Membercard())->getMembercardlist();
        foreach ($cardlist as $k=>$v){
            $cardlist[$k]['child'] = (new Membercardxz())->getMembercardxzInfo($v['id']);
        }
        $usercardinfo['card'] =$cardlist;
        return Show::json_show(Status::mini_normal, "获取用户会员卡成功", $usercardinfo);
    }

    /**
     * 我的收货地址列表
     * @return \think\response\Json
     */
    public function myaddress(){
        $openid =$this->request->param('openid','','trim');

        try{
            $address= (new Address())->getaddresslist([['openid','=',$openid]],'id,isdefault,lng,lat,locatarea,realname,mobile,address');
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,'获取失败');
        }
        return Show::json_show(Status::mini_normal, "获取用户地址成功", $address);
    }

    /**
     * @return \think\response\Json
     */
    public function doOptionAddress(){
        $openid = $this->request->param('openid', '', 'trim');
        $realname = $this->request->param('realname', '', 'trim');
        $address = $this->request->param('address', '', 'trim');
        $mobile = $this->request->param("mobile", '', 'trim');
        $isdefault = $this->request->param("isdefault", '1', 'trim');
        $lng = $this->request->param("lng", '', 'trim');
        $lat = $this->request->param("lat", '', 'trim');
        $area = $this->request->param("area", '', 'trim');
        $address_id = $this->request->param("address_id", '0', 'intval');
        $data = [
            'id' =>$address_id,
            "openid" => $openid,
            "realname" => $realname,
            "mobile" => $mobile,
            "lng" => $lng,
            "lat" => $lat,
            "locatarea" => $area,
            "address"=>$address,
            "isdefault" =>$isdefault
        ];

        try{
            $result= (new Address())->updateByData($data);
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,$e->getMessage());
        }
        return Show::json_show(Status::mini_normal, "编辑成功", []);
    }

    /**
     *  设置默认收货地址
     * @return \think\response\Json
     * @throws \think\Exception
     */
    public function setDefaultAddress(){

        $openid = $this->request->param('openid', '', 'trim');
        $address_id = $this->request->param("address_id", '0', 'intval');
        try{
            $addressinfo=(new Address())->getaddressInfo([['id','=',$address_id]],'*');
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,$e->getMessage());
        }
        if($addressinfo){
            $result= (new Address())->saveData([['openid','=',$openid]],array('isdefault'=>0));
            $data =array('isdefault'=>1,'id'=>$address_id);
            $addressinfo->save($data);
        }
        return Show::json_show(Status::mini_normal, "设置成功", []);
    }


    /**
     * 删除收货地址
     * @return void
     */
    public function deleteAddress(){
        $openid = $this->request->param('openid', '', 'trim');
        $address_id = $this->request->param("address_id", '0', 'intval');
        try{
            $addressinfo=(new Address())->getaddressInfo([['id','=',$address_id]],'*');
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,$e->getMessage());
        }
        if($addressinfo){
            $result= (new Address())->deleteByAddress([['id','=',$address_id]]);
        }
        return Show::json_show(Status::mini_normal, "删除成功", []);
    }

    /**
     * 商家入驻信息
     * @return void
     */
    public function applyToInfo(){
        $type =$this->request->param('type','2','intval'); // 默认商家分类
        try{
            $catlist= (new Cate())->getCateList([['status','=',1],['type','=',$type]],'id,title as name');
            $ainfo =(new Agreement())->getAgreementInfo('1');
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,$e->getMessage());
        }

        return Show::json_show(Status::mini_normal, "获取成功", [
            'cats' =>$catlist,
            'agreement' =>$ainfo['content']
        ]);
    }


    /**
     * 申请入驻商家
     * @return void
     */
    public function applyToManager(){
        $openid =$this->request->param('openid','','trim');  //微信openid
        $realname =$this->request->param('realname','','trim'); // 联系人
        $mobile =$this->request->param('mobile','','trim'); //联系电话
        $weixinno =$this->request->param('weixinno','','trim'); // 核销微信
        $title =$this->request->param('title','','trim');  // 店铺名称
        $servicetel =$this->request->param('servicetel','','trim'); // 电话
        $lng =$this->request->param('lng','','trim');
        $lat =$this->request->param('lat','','trim'); // 市
        $area =$this->request->param('area','','trim'); // 区
        $address =$this->request->param('address','','trim'); // 电话
        $cat_id =$this->request->param('cat_id','','trim'); // 商家类目
        $company =$this->request->param('company','','trim'); // 公司名称
        $company_tel =$this->request->param('company_tel','','trim'); // 电话
        $cardimg =$this->request->param('cardimg','','trim'); // 商家资质

        $data =array(
            'openid' => $openid,
            'realname' =>$realname,
            'mobile' => $mobile,
            'weixinno' =>$weixinno,
            'title'   =>$title,
            'servicetel' =>$servicetel,
            'lng' =>$lng,
            'lat'   =>$lat,
            'area'   =>$area,
            'address'=>$address,
            'cat_id' =>$cat_id,
            'company'=>$company,
            'company_tel'=>$company_tel,
            'cardimg' =>json_encode($cardimg),
            'applystatus'=>0,
            'apply_reason'=>''
        );

        if(!$cardimg){
            return Show::json_show(Status::mini_error,'请上传资质文件');
        }

        try{
            $result=(new Manager())->saveData($data);
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,$e->getMessage());
        }

        return Show::json_show(Status::mysql_normal,'提交申请成功',[]);
    }

    /**
     * 商家详情
     * @return \think\response\Json
     */
    public function getManagerInfo(){
        $openid =$this->request->param('openid','','trim');  //微信openid
        try{
            $info =(new Manager())->getManagerInfo([['openid','=',$openid]],'*');
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,$e->getMessage());
        }

        if($info && !empty($info['cardimg']) && is_array($info['cardimg'])){
            $cardimg =json_decode($info['cardimg'],true);
            $info['cardimg'] =$cardimg;
        }
        return Show::json_show(Status::mysql_normal,'获取成功',[
            'manager' =>$info??[]
        ]);
    }

    /**
     * 商家发布商品
     * @return \think\response\Json
     */
    public function fabuGoods(){
        $openid =$this->request->param('openid','','trim');  //微信openid
        $title =$this->request->param('title','','trim'); // 商品名称
        $cat_id =$this->request->param('cate_id','0','intval');
        $goods_price =$this->request->param('goods_price','','trim'); //商品价格
        $market_price =$this->request->param('market_price','','trim'); // 原价
        $stock =$this->request->param('stock','','trim');  // 库存
        $desc =$this->request->param('desc','','trim');  // 商品详情
        $mendian =$this->request->param('mendian'); // 门店信息
        $goodsimg =$this->request->param('images'); // 主图数组
        $descimg =$this->request->param('descimg'); // 详情图数组
        $g_id =$this->request->param('gid','','intval');

        $data =array(
            'id'   =>$g_id,
            'openid' => $openid,
            'title' =>$title,
            'title_desc' => $title,
            'goods_price' =>$goods_price,
            'market_price'   =>$market_price,
            'stock' =>$stock,
            'total_stock' =>$stock,
            'cate_id'     =>$cat_id,
            'mendian'   =>json_encode($mendian)
        );
        $images ='';
        if(is_array($goodsimg) && $goodsimg){
            foreach ($goodsimg as $k=>$v){
                $images.=$v['url'].'|';
            }
            $images =substr($images,0,-1);
            $data['images'] =$images;
            $data['logo'] =$goodsimg[0]['url'];
        }else{
            return Show::json_show(Status::mini_error,'请上传图片1');
        }

        if(!is_array($descimg)){
            return Show::json_show(Status::mini_error,'请上传图片2');
        }

        $data['description'] ="<p>".$desc."</p><p>";
        foreach ($descimg as $k=>$v){
            $data['description'].="<img src='".$v['url']."' style='width:100%;'><br>";
        }
        $data['description'].="</p>";
        try{
            $managerinfo = (new Manager())->getManagerInfo([['openid','=',$openid],['applystatus','=',1]],'*');
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,$e->getMessage());
        }
        if(!$managerinfo){
            return Show::json_show(Status::mini_error,'商家不存在，系统错误');
        }
        $data['manager_id'] =$managerinfo['id'];
        try{
            $result=(new Goods())->saveData($data);
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,$e->getMessage());
        }

        return Show::json_show(Status::mysql_normal,'上传成功',[]);
    }

    /**
     * 商品审核记录
     * @return false|string|\think\response\Json
     */
    public function  applyGoodsList(){
        $openid =$this->request->param('openid','','trim');  //微信openid
        try{
            $list= (new Goods())->getManagerByGoods($openid);
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,$e->getMessage());
        }
        return Show::json_show(Status::mysql_normal,'获取成功',[
            'applylist' =>$list
        ]);
    }

    /**
     * 会员卡购买
     * @return \think\response\Json
     * @throws \ReflectionException
     * @throws \think\Exception
     */
    public function userToPay(){
        $openid =$this->request->param('openid','','trim');  //微信openid
        $card_id =$this->request->param('card_id','','intval');

        try{
            $cardinfo= (new Membercard())->getMembercardInfo($card_id);
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,$e->getMessage());
        }
        if(!$cardinfo){
            return Show::json_show(Status::mini_error,'系统异常');
        }
        $data=array(
            'ordersn' =>Str::RandomStr(),
            'openid' =>$openid,
            'money'  =>$cardinfo['price'],
            'card_id' =>$card_id,
            'id'=>''
        );
        try{
            $result= (new MemberPaylog())->saveData($data);
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,$e->getMessage());
        }
        if($result){
            $objClass = ArrClass::payAttr();
            $obj = ArrClass::initClass('wx',$objClass,[],true);
            $data = [
                'body' => '同城生活购买会员卡',
                'out_trade_no' => $data['ordersn'],
                'total_fee' => $data['money']*100,
                'spbill_create_ip' => $this->request->ip(), // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
                'notify_url' => 'https://life.jixuantiant.com/api/index/paynotify', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
                'attach' =>'paycard',
                'openid' => $openid,
            ];
            $jsondata = $obj->order($data);
            $wechatpay= $obj->jssdk($jsondata['prepay_id']);
        }
        return Show::json_show(Status::mysql_normal,'返回成功',[
            'wechat' =>json_decode($wechatpay,true)
        ]);
    }

    /**
     * 核销生成二维码
     * @return mixed
     */
    public function getGroupCode(){
        $order_id =$this->request->param('order_id','','intval'); // 团购订单id
        //file_put_contents('a0001.txt',$order_id.PHP_EOL,8);
        try{
            $orderinfo= (new \app\common\business\Group())->getOrderById($order_id);
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,'查询失败');
        }
        //file_put_contents('a0002.txt',var_export($orderinfo,true).PHP_EOL,8);
        if(!$orderinfo){
            return Show::json_show(Status::mini_error,'订单不存在');
        }
        $filename='';
        // 生产二维码
        $response = $this->mini_app->app_code->getUnlimit('heorder_'.$order_id, [
            'page'  => 'pages/index/index',
            'width' => 600,
        ]);
        // $response 成功时为 EasyWeChat\Kernel\Http\StreamResponse 实例，失败为数组或你指定的 API 返回类型
        //file_put_contents('a0003.txt',var_export($response,true).PHP_EOL,8);
        // 保存小程序码到文件
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $filename = $response->save(public_path('upload/wxcode/'));
           // file_put_contents('a0004.txt',var_export($filename,true).PHP_EOL,8);
        }

        return Show::json_show(Status::mysql_normal,'返回成功',[
            'qrcode' =>'https://'.$_SERVER['HTTP_HOST']. '/upload/wxcode/'.$filename
        ]);
    }

    /**
     * 判断商家是否入驻成功
     * @return void
     */
    public function getManagerApplayStatus(){
        $openid =$this->request->param('openid','','trim');
        try{
            $info=(new Manager())->getManagerInfo([['openid','=',$openid]],'*');
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,'查询失败');
        }
        if($info && $info['applystatus'] ==1 && $info['status']==1){
            $apply =1;
        }else{
            $apply =0;
        }
        return Show::json_show(Status::mysql_normal,'返回成功',[
            'status' =>$apply,
            'minfo' =>$info??[]
        ]);
    }

    /**
     * 支付保证金
     * @return \think\response\Json
     * @throws \ReflectionException
     * @throws \think\Exception
     */
    public function payShopBzj(){
        $openid =$this->request->param('openid','','trim');
        try{
            $info=(new Manager())->getManagerInfo([['openid','=',$openid]],'*');
            $config =(new SystemConfig())->where([['name','=','shopbzj']])->find();
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,'查询失败');
        }
        if(!$info){
            return Show::json_show(Status::mini_error,'商家异常');
        }

        if($info['paystatus']==1){
            return Show::json_show(Status::mini_normal,'已支付保证金，无需重复支付',['status'=>2]);
        }

        if(!$config || ($config && round($config['value'],2)<=0)){
            return Show::json_show(Status::mini_normal,'保证金无需支付',['status'=>2]);
        }
        // 写入支付记录表

        $pdata = array('ordersn' => Str::RandomStr(), 'id' => '', 'type' => 6, 'openid' => $openid, 'money' => $config['value']);
        (new MemberPaylog())->saveData($pdata);
        $objClass = ArrClass::payAttr();
        $obj = ArrClass::initClass('wx', $objClass, [], true);
        $data = [
            'body' => '同城生活商城下单',
            'out_trade_no' => $pdata['ordersn'],
            'total_fee' => $config['value'] * 100,
            'spbill_create_ip' => $this->request->ip(), // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            'notify_url' => 'https://life.jixuantiant.com/api/index/paynotify', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'attach' => 'shopbzj',
            'openid' => $openid,
        ];
        $jsondata = $obj->order($data);
        $wechatpayobject = $obj->jssdk($jsondata['prepay_id']);
        $wechatpay =json_decode($wechatpayobject, true);
        return Show::json_show(Status::mini_normal, "ok", [
            'wechat' => $wechatpay,
            'status'=>1
        ]);
    }



    /**
     * 判断商家是否入驻成功
     * @return void
     */
    public function getManagerApplayStatus2(){
        $openid =$this->request->param('openid','','trim');
        try{
            $info=(new Manager())->getManagerInfo([['openid','=',$openid]],'*');
            $log =(new MemberPaylog())->getByBzjType(6,$openid);
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,'查询失败');
        }
        if(!$info){
            $apply ='-1';
            $info['paystatus']=0;
        }else{
            $apply =$info['applystatus'];
        }

        if(!$log){
            $bzjstatus =0;
        }else{
            $bzjstatus =$log['bzjstatus'];
        }

        return Show::json_show(Status::mysql_normal,'返回成功',[
            'status' =>$apply,
            'paystatus'=>$info['paystatus'],
            'bzjstatus'=>$bzjstatus,
            'log'=>$log
        ]);
    }

    public function getPayLogInfo(){
        $openid =$this->request->param('openid','','trim');
        $id =$this->request->param('id','','intval');
        $bankname =$this->request->param('bankname','','trim');
        $realname =$this->request->param('realname','','trim');
        $bankno =$this->request->param('bankno','','trim');
        try{
            $log =(new MemberPaylog())->getByLogId($id);
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,'查询失败');
        }
        if(!$bankname || !$realname || !$bankno){
            return Show::json_show(Status::mini_error,'请填写完整信息');
        }

        if(!$log || in_array($log['bzjstatus'],[1,2])){
            return Show::json_show(Status::mini_error,'非法操作');
        }


        try{
            $data=['id'=>$id,'bzjstatus'=>1,'realname'=>$realname,'bankname'=>$bankname,'bankno'=>$bankno,'bzj_reason'=>''];
            $res =(new MemberPaylog())->saveData($data);
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,'查询失败');
        }

        return Show::json_show(Status::mini_normal,'申请成功',[]);
    }


    /**
     * 我的钱包明细
     * @return mixed
     */
    public function myWallet(){
        $openid =$this->request->param('openid','','trim');
        $page =$this->request->param('page','1','intval');
        $starttime =$this->request->param('starttime','','trim');
        $endtime =$this->request->param('endtime','','trim');
        $type =$this->request->param('type','1','intval'); // 1消费明细  2收入明细
        try{
            $list =(new Member())->getAccountLog($openid,$type,$page,$starttime,$endtime);
            $member =(new Wechat())->getOpenidById($openid);
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,'查询失败');
        }
        return Show::json_show(Status::mysql_normal,'返回成功',[
            'mingxi' =>$list,
            'balance'=>$member['balance']
        ]);
    }

    /**
     * 零钱提现
     * @return mixed
     */
    public function withdrawal(){
        $openid =$this->request->param('openid','','trim');
        $money =$this->request->param('money','','trim');

        $withdrawal_min =(new Member())->getSystenConfig('withdrawal_min');
        $withdrawal_max =(new Member())->getSystenConfig('withdrawal_max');
        $withdrawal_num =(new Member())->getSystenConfig('withdrawal_num');

        if($money<$withdrawal_min || $money>$withdrawal_max){
            return Show::json_show(Status::mini_error,'提现金额未满足要求');
        }

        // 最近一次提现
        try{
            $member =(new Wechat())->getOpenidById($openid);
            $info = (new Member())->getWithdrawal($openid);

        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,'用户异常');
        }
        if(!$member || ($member && $member['balance'] < $money)){
            return Show::json_show(Status::mini_error,'余额不足，请稍后重试');
        }
        if($info){
            if((strtotime($info['create_time'])+$withdrawal_num*60*60)>time()){
                return Show::json_show(Status::mini_error,$withdrawal_num.'小时后才能再次提现');
            }
        }

        $isdirect=1;  // 需要更换系统参数
        $withdrawalmodel =(new MallWithdrawal());
        // 写入申请表
        try{

            $data =array(
                'openid' =>$openid,
                'money' =>$money,
                'status' =>0,
                'ordersn'=>Str::RandomStr(),
                'datetime' =>date('Y-m-d')
            );
            if($isdirect==0){
                $result= (new Member())->saveWithdrawal($data);
            }else{
                $objClass = ArrClass::payAttr();
                $obj = ArrClass::initClass('wx', $objClass, [], true);
                // 提现接口
                $notify= $obj->transfer([
                    'partner_trade_no' => $data['ordersn'], // 商户订单号，需保持唯一性(只能是字母或者数字，不能包含有符号)
                    'openid' => $openid,
                    'check_name' => 'NO_CHECK', // NO_CHECK：不校验真实姓名, FORCE_CHECK：强校验真实姓名
                    're_user_name' => '', // 如果 check_name 设置为FORCE_CHECK，则必填用户真实姓名
                    'amount' => $money*100, // 企业付款金额，单位为分
                    'desc' => '同城生活钱包提现', // 企业付款操作说明信息。必填
                ]);
                if($notify && $notify['return_code'] == 'SUCCESS'){
                    if($notify['result_code'] == 'SUCCESS'){
                        (new Member())->saveWithdrawal($data);
                        $withdrawalmodel->where(" ordersn ='".$data['ordersn']."'")->save(array('status'=>1));
                        (new Member())->saveAccoutLog($openid,$money,2,'会员提现');
                    }else{
                        return Show::json_show(Status::mini_error,$notify['err_code_des']);
                    }
                }
                else{
                    return Show::json_show(Status::mini_error,'提现失败');
                }
            }
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,'提现失败');
        }

        return Show::json_show(Status::mysql_normal,'操作成功',[

        ]);
    }

    /**
     * 商城订单申请售后
     * @return \think\response\Json
     */
    public  function orderToRefund(){
        $openid =$this->request->param('openid','','trim');
        $order_id =$this->request->param('order_id','','trim');
        $type =$this->request->param('type','','trim');
        $reason =$this->request->param('reason','','trim');
        $remark =$this->request->param('remark','','trim');
        $mobile =$this->request->param('mobile','','trim');
        $imgs =$this->request->param('imgs','','trim');

        if(!$reason || !$type || !$remark){
            return Show::json_show(Status::mini_error,'退款必要信息请填写完整');
        }
        if (!preg_match('/^(?:(?:\+|00)86)?1[3-9]\d{9}$/', $mobile)) {
            return Show::json_show(Status::mini_error, '联系电话输入有误');
        }
        try{
            $orderinfo =(new Orders())->getOrderInfoById($order_id,$openid);
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,'查询失败');
        }
        if(!$orderinfo){
            return Show::json_show(Status::mini_error,'订单不存在');
        }
        $data =array(
            'openid' =>$openid,
            'order_id'=>$order_id,
            'refund_type' =>$type,
            'refund_reason'=>$reason,
            'remark'    =>$remark,
            'mobile'=>$mobile,
            'refund_money' =>$orderinfo['payprice']
        );
        if($imgs && is_array($imgs)){
            $data['refund_imgs'] =json_encode($imgs);
        }

        try{
            $result=(new MallOrderRefund())->save($data);
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,'申请失败');
        }
        if($result){
            $orderdata=array('id'=>$order_id,'isapplyrefund'=>1);
            (new Orders())->saveData($orderdata);
        }
        return Show::json_show(Status::mysql_normal,'操作成功',[
        ]);
    }
    /**
     * 拼团订单申请售后
     * @return \think\response\Json
     */
    public  function groupOrderToRefund(){
        $openid =$this->request->param('openid','','trim');
        $ordersn =$this->request->param('ordersn','','trim');
        $order_id =$this->request->param('order_id','','trim');
        $type =$this->request->param('type','','trim');
        $reason =$this->request->param('reason','','trim');
        $remark =$this->request->param('remark','','trim');
        $mobile =$this->request->param('mobile','','trim');
        $imgs =$this->request->param('imgs','','trim');

        if(!$reason || !$type || !$remark){
            return Show::json_show(Status::mini_error,'退款必要信息请填写完整');
        }
        if (!preg_match('/^(?:(?:\+|00)86)?1[3-9]\d{9}$/', $mobile)) {
            return Show::json_show(Status::mini_error, '联系电话输入有误');
        }
        try{
            $orderinfo =(new \app\common\business\Group())->getOrderByOrdersn($openid,$ordersn,'*');
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,'查询失败');
        }
        if(!$orderinfo){
            return Show::json_show(Status::mini_error,'订单不存在');
        }

        if($orderinfo['isverify']==1){
            return Show::json_show(Status::mini_error,'核销订单不能提交售后');
        }

        $data =array(
            'openid' =>$openid,
            'order_id'=>$order_id,
            'refund_type' =>$type,
            'refund_reason'=>$reason,
            'remark'    =>$remark,
            'mobile'=>$mobile,
            'refund_money' =>$orderinfo['payprice']
        );
        if($imgs && is_array($imgs)){
            $data['refund_imgs'] =json_encode($imgs);
        }

        try{
            $result=(new MallGroupsOrderRefund())->save($data);
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,'申请失败');
        }
        if($result){
            $orderdata=array('isapplyrefund'=>1,'status'=>3);
            (new MallGroupsOrder())->where("id='$order_id'")->save($orderdata);
        }
        return Show::json_show(Status::mysql_normal,'操作成功',[
        ]);
    }

    // 确认核销接口
    public function doHexiao(){
        $orderscane =$this->request->param('scane', '', 'trim'); // 核销二维码参数
        $openid =$this->request->param('openid', '', 'trim');    //商家核销人openid
        if($orderscane){
            $order_ids =explode('_',$orderscane);
            $order_id =$order_ids[1];
            try{
                $orderinfo= (new \app\common\business\Group())->getOrderAndManager($order_id);
            }catch (\Exception $e){
                return Show::json_show(Status::mini_error,'查询失败');
            }
            if(!$orderinfo){
                return Show::json_show(Status::mini_error,'订单异常');
            }
            if(!$orderinfo || ($orderinfo && ($orderinfo['status'] !=1 || ($orderinfo['status']==1 && $orderinfo['isverify']==1)))){
                return Show::json_show(Status::mini_error,'核销失败');
            }
            $manager =(new MallManager())->where([['id','=',$orderinfo['manager_id']]])->find();
            if(!$manager || (!empty($manager) && $manager['openid'] != $openid)){
                return Show::json_show(Status::mini_error,'核销失败');
            }
            try{
                $res=(new MallGroupsOrder())->where("id='".$orderinfo['id']."'")->save(array('isverify'=>1,'verifytime'=>time()));
            }catch (\Exception $e){
                return Show::json_show(Status::mini_error,'核销失败');
            }
        }else{
            return Show::json_show(Status::mini_error,'核销失败');
        }
        if($res){
            // 核销返利 --- 取消不要 By 2022-3-17
//            if(!empty($orderinfo['parent_openid'])){
//                (new Member())->saveAccoutLog($orderinfo['parent_openid'],$orderinfo['first_price'],3, '分享返利');
//            }

        }
        return Show::json_show(Status::mysql_normal,'核销成功',[
            'info'=>$orderinfo
        ]);
    }

}